<template>
  <div class="shop">
		<div class="nav clearfix">
			<div class="back fl">
				<span @click="historyBack()"></span>
			</div>
			<div class="title fl">
        <a href="#/" class="ico-home" style="position:absolute; right:1.8rem; top:0.45rem; width:1rem; height:1rem;"></a>
				<span>{{defaultType}}</span>
			</div>
			<div class="cart fr">
				<span class="icon fr" @click="gotoAddress()"></span>
				<span class="count fr" v-if="cartNum !=0">{{cartNum}}</span>
			</div>
		</div>
    <div class="type-box">
      <div class="type-item-all">
        <div class="type-item" @click="taggleType()">
          <span class="font">{{defaultType}}</span>
          <span class="ico" :class="{active:isShowType}"></span>
        </div>
        <div class="line"></div>
        <div class="type-item" @click="taggleBrand()">
          <span class="font" v-html="defaultBrand"></span>
          <span class="ico" :class="{active:isShowBrand}"></span>
        </div>
        <div class="line"></div>
        <div class="type-item" @click="taggleOrder()">
          <span class="font">{{defaultSort}}</span>
          <span class="ico" :class="{active: isShowOrder}"></span>
        </div>
      </div>
      <div class="item-content">
        <div class="con-item" v-show="isShowType">
          <div class="type">

            <mt-cell style="height:3rem;" :title="item.name" v-for="item in categorysub" :key="item.category_id" :class="{'color-red':item.name==defaultType}">

              <img slot="icon" :src="item.image"/>
              <!--解决点击没有效-->
              <div @click="chooseItemByCategory(item.category_id,item.name)" style="color:red" class="item-absolute"></div>
            </mt-cell>
          </div>
        </div>
        <div class="con-item" v-show="isShowBrand">
          <div class="brand-box">

            <div class="brand-list">
              <div v-for="(brand,index) in brandList">

                <div class="sub-tt" :id="index">{{index}}</div>

                <div class="list clearfix" v-for="item in brand"
                     @click="chooseItemByBrand(item.manufacturer_id,item.name)" :class="{'background-red':item.name==defaultBrand}">
                  <div class="fl">
                    <img :src="item.image" alt="">
                  </div>
                  <div class="fc" v-html="item.name"></div>
                </div>
              </div>
            </div>

            <div class="brand-tap">
              <ul class="tap">
                <li v-for="(item,index) in brandList"><a href="javascript:;" @click="myScrollTo(index)">{{index}}</a>
                </li>
              </ul>
            </div>


          </div>
        </div>
        <div class="con-item" v-show="isShowOrder">

          <mt-cell :title="item.title" v-for="(item,index) in sortList" :key="index" :class="{'color-red':item.title==defaultSort}" style="height:3rem; line-height: 3rem; text-align: center;">
            <div @click="chooseItemByOrder(item.order,item.title)" class="item-absolute"></div>
          </mt-cell>
        </div>
      </div>
    </div>
    <div class="goddess-rec">
      <div class="rec-box" v-if="isShowProductList">
        <ul class="rec-list clearfix">

          <li class="rec-li" v-for="item in categoryList">
            <div class="img">
              <a @click="redirect(item.product_id)">
                <img v-if="item.thumb!=null" :src="item.thumb" :onerror="logo" alt="">
                <img v-if="item.thumb==null" src="../../assets/default.png" alt="">
              </a>
            </div>
            <div class="rec-t">
              <a @click="redirect(item.product_id)">{{item.name}}</a>
            </div>
            <div class="price-b clearfix">
              <div class="fl"><span class="price">{{item.price}}</span></div>
              <div class="fr">
                <span class="shoucang" :class="{ 'active': collectMap[item.product_id]}"
                      @click="toggleCollectStatus(item.product_id)"></span>
              </div>
            </div>
          </li>
        </ul>
      </div>
      <div class="rec-no-product" v-if="!isShowProductList">
        <p>没有搜索到您想要的商品...</p>
      </div>
    </div>
    <span class="buy" @click="gotoAddress()"><i v-if="cartNum !=0" class="mint-badge is-success is-size-small">{{cartNum}}</i></span>

  </div>
</template>

<script>
  import {Toast} from 'mint-ui';
  import {Indicator} from 'mint-ui';
//import {Radio} from 'mint-ui'
  export default {
    name: 'ShopType',
    data () {
      return {
        brandList: {},//品牌列表
        categorysub: [],
        categoryList: [],
        sortList: [
          {title: "默认", order: 'p.price'},
          {title: '最新上架', order: 'ASC'},
          {title: '人气价格', order: 'DESC'},
          {title: '价格最低', order: 'p.price'}
        ],
        defaultType: '分类',
        defaultBrand: '品牌',
        defaultSort: '智能排序',
        arr2: [],
        isShowProductList: false,
        isShowType: false,
        isShowBrand: false,
        isShowOrder: false,
        cid: "",//分类,
        sort: '',
        order: '', //ASC升序，DESC降序
        manufacturer_id: 0,
        formData: null, //排序的formData
        collectMap: {},
        cartNum: 0,
        logo: 'this.src="' + require('../../assets/default.png') + '"'
      }
    },
    methods: {
      myScrollTo: function (id) {
        let top = $('#' + id).offset().top - 30;
        $('.item-content').scrollTop(top);
      },
      redirect: function (id) {
        this.$router.push({path: '/shop/details/' + id});
      },
      historyBack(){
      	this.$router.go(-1);
      },
      gotoAddress(){
        let path = '/me/shopping';
        this.$router.push(path)
      },

      //按类别选择包包，如手提包，单肩包，钱包等等
      chooseItemByCategory(category_id, type){
        this._reset_Type_Brand_Order();
        this.defaultType = type;
//        console.log(type);
        if (this.cid == category_id) {
          return;
        }
        this.cid = category_id;
        this.getCategoryList()
      },
      //按品牌选择
      chooseItemByBrand(brandId, name){
        this._reset_Type_Brand_Order();
        this.defaultBrand = name;
        if (this.manufacturer_id === brandId)
          return;
        this.manufacturer_id = brandId;

        this.getCategoryList()
      },
      chooseItemByOrder(order, name){
        this._reset_Type_Brand_Order();
        this.defaultSort = name;
        if (this.order === order)
          return;
        if (order !== "p.price") {
          this.order = order;
        }
        else
          this.sort = order;
        this.getCategoryList()

      },
      //查看是否有收藏
      wishList: function (id) {
        let ajaxData = {};
        ajaxData.token = sessionStorage.user && JSON.parse(sessionStorage.user).token;
        if (!ajaxData.token) {
          return false;
        }

        let position = this.arr2.indexOf(id);
        if (position > -1) {
          this.$set(this.collectMap, id, true);
          return true;
        }
        return false;
      },
      toggleCollectStatus(id){
        let token = sessionStorage.user && JSON.parse(sessionStorage.user).token;
        if (!token) {
          this.$router.push({
            path: '/login',
            query: {
              redirect: this.$route.fullPath
            }
          });
          return;
        }
        else if (!this.collectMap[id]) {
          this._addWishlist(id);
        }
        else {
          this._removeWishlist(id);
        }

      },
      _addWishlist: function (id) {
        var _this = this;
        var ajaxData = {};
        ajaxData.token = sessionStorage.user && JSON.parse(sessionStorage.user).token;
        ajaxData.product_id = id;
        $.ajax({
          type: 'post',
          url: RouteMap.wishlistAdd,
          data: ajaxData,
          success: function (res) {
            if (res.code == 200) {
              console.log(id);
              _this.$set(_this.collectMap, id, true);
              Toast("收藏成功");
            }
            else {
              _this.$set(_this.collectMap, id, false);
              //Toast(res.msg)
            }
          }
        })
      },
      _removeWishlist: function (id) {
        let ajaxData = {};
        let _this = this;
        ajaxData.token = sessionStorage.user && JSON.parse(sessionStorage.user).token;
        ajaxData.product_id = id;
        $.ajax({
          type: 'post',
          url: RouteMap.wishlistRemove,
          data: ajaxData,
          success: function (res) {
            if (res.code == 200) {
              _this.$set(_this.collectMap, id, false);
              Toast("取消收藏");
            }
            else {
              _this.$set(_this.collectMap, id, true);
              //Toast(res.msg)
            }
          },
          error: function () {
            Toast("发生未知错误");
          }
        })

      },
      //得到收藏列表
      getWish: function () {
        let ajaxData = {};
        let arr = [];
        let _this = this;
        ajaxData.token = sessionStorage.user && JSON.parse(sessionStorage.user).token;
        if (!ajaxData.token) {
          return;
        }
        $.ajax({
          type: 'post',
          url: RouteMap.wishlistGet,
          data: ajaxData,
          success: function (res) {
            if (res.code == 200) {
              arr = res.data.products;
              for (var i = 0; i < arr.length; i++) {
                _this.arr2.push(arr[i].product_id);
              }
              _this.getCategoryList();
            }
            else {
              //Toast(res.msg)
            }
          }
        })
      },

      //重置属性
      _reset_Type_Brand_Order(){
        this.isShowType = false;
        this.isShowBrand = false;
        this.isShowOrder = false;
      },
      taggleType(){
        this.isShowType = !this.isShowType;
        this.isShowBrand = false;
        this.isShowOrder = false;
      },
      taggleBrand(){
        this.isShowBrand = !this.isShowBrand;
        this.isShowType = false;
        this.isShowOrder = false;
      },
      taggleOrder(){
        this.isShowOrder = !this.isShowOrder;
        this.isShowType = false;
        this.isShowBrand = false;
      },
      //初始化提交表单的数据
      _initFormData(){
        if ((!this.cid) && (!this.sort) && (!this.manufacturer_id) && !(this.order)) {
          return;
        }
        this.formData = new FormData();
        this.formData.append('cid', this.cid);
        this.formData.append("sort", this.sort);
        this.formData.append("order", this.order);
        this.formData.append("manufacturer_id", this.manufacturer_id);
      },

      _getRouteParams(){
        this.cid = this.$route.query.type;
        this.defaultType = this.$route.query.typeName;
      },

      getCategoryList(){
        this._initFormData();
        let _this = this;
        Indicator.open({
          text: "数据更新中...",
          spinnerType: 'fading-circle'
        });
        $.ajax({
          type: 'post',
          url: RouteMap.categoryList,
          data: _this.formData,
          contentType: false,
          processData: false,
          success: function (res) {
            Indicator.close();
            if (res.code == 200) {
              if (res.data.products) {
                _this.isShowProductList = true;
                _this.categoryList = res.data.products;
                let length = _this.categoryList.length;
                for (let i = 0; i < length; i++) {
                  _this.wishList(_this.categoryList[i].product_id);
                }
              }
              else {
                _this.isShowProductList = false;
              }
            }
            else {
              //Toast(res.msg)
            }
          },
          error: function () {
            Indicator.close();
            Toast("发生未知错误");
          }
        })
      },
      getCartNum: function () {
        var token = sessionStorage.user && JSON.parse(sessionStorage.user).token;
        var _this = this;
        if (!token) {
          return;
        }
        var ajaxData = {};
        ajaxData.token = token;

        setTimeout(function () {
          $.ajax({
            type: 'post',
            url: RouteMap.cartNum,
            data: ajaxData,
            cache: false,
            success: function (res) {
              if (res.code == 200) {

                _this.cartNum = res.data.num;

              }
              else {
                //Toast(res.msg)
              }
            }
          })
        }, 100)

      }
    },
    mounted: function () {
      let _this = this;

      let category_id = this.$route.query.type;
      let type = this.$route.query.typeName;
//      console.log(category_id);
//      console.log(type);
      _this.chooseItemByCategory(category_id, type);
      //初始化数据 点击进入分类页面,要获取数据 2017-12-16
      let categorysubData = {};
      categorysubData.parent_id = 1;
      this._getRouteParams();
      this.getCartNum();
      $.ajax({
        type: 'post',
        url: RouteMap.categorysub,
        data: categorysubData,
        success: function (res) {
          if (res.code == 200) {
            _this.categorysub = res.data;
          }
          else {
            //Toast(res.msg)
          }
        }
      });
      setTimeout(function () {
        $.ajax({
          type: 'post',
          url: RouteMap.brandList,
          success: function (res) {
            if (res.code == 200) {
              _this.brandList = res.data;
            }
            else {
              //Toast(res.msg)
            }
          }
        })
      });
      setTimeout(function(){
        _this.getWish();
      });

    },
    components: {}
  }
</script>

<style scoped>
  .shop {
    background: #fff;
    color: #707070;
  }
	.nav{
		width:100%;
		height: 2rem;
		font-size: .6rem;
		border-bottom:1px solid #c2c2c2;
		display: flex;
	}
	.nav div{
		flex: 1;
	}
	.nav .back{
		margin: auto 0;
	}
	.nav .back span{
		display: block;
		width: 0.4rem;
		height: 0.8rem;
		margin-left: 0.6rem;
		background: url("../../assets/shoptype/back.png");
		background-size: 100% 100%;
	}
	.nav .title{
		text-align: center;
		line-height: 2rem;
	}
	.nav .cart{
		margin: auto 0;
	}
	.nav .cart .count{
		width: 0.8rem;
		height: 0.8rem;
		line-height: 0.8rem;
		margin-right: 0.1rem;
		border-radius: 50%;
		background: #b01f24;
		color:#FFFFFF;
		line-height: 0.8rem;
		text-align: center;
		font-size: 0.6rem;
	}
	.nav .cart .icon{
		width: 0.8rem;
    height: 0.8rem;
    margin-right: 0.4rem;
    background: url("../../assets/shoptype/carticon.png");
    background-size: 100% 100%;
	}
  .type-box {
    border-bottom: 1px solid #c2c2c2;
    font-size: 0;
    position: relative;

  }

  .type-box .item-content {
    position: absolute;
    width: 100%;
    background: #fff;
    max-height: 15rem;
    top: 2rem;
    opacity: 1;
    overflow-y: auto;
    z-index: 100;
  }

  .raido {
    display: inline-block;
    width: .6rem;
    height: .6rem;
    background: url("../../assets/sale/radio.png") 0 0 no-repeat;
    background-size: 100% 100%;
  }

  .raido-active {
    display: inline-block;
    width: .6rem;
    height: .6rem;
    background: url("../../assets/sale/radio-active.png") 0 0 no-repeat;
    background-size: 100% 100%;
  }

  .type-box .type-item {
    display: inline-block;
    width: 5.3rem;
    text-align: center;
    height: 2rem;
    line-height: 2rem;
    vertical-align: middle;
    font-size: .6rem;
    white-space: nowrap;
    text-overflow: clip;
  }

  .type-box .line {
    display: inline-block;
    width: 1px;
    background: #707070;
    height: .7rem;
    vertical-align: middle;
  }

  .type-box .ico {
    width: .6rem;
    height: .3rem;
    display: inline-block;
    background: url("../../assets/shop/ico8.png");
    background-size: 100% auto;
  }

  .type-box .ico.active {
    background: url("../../assets/shop/ico8-ac.png");
    background-size: 100% auto;
  }

  .type-item span {
    display: inline-block;
    vertical-align: middle;
    white-space: nowrap;
    text-overflow: clip;
    color: #707070;
  }

  .goddess-rec {
    background: #fff;
    margin-top: .5rem;
    padding-left: .23rem;
    padding-bottom: .5rem;
    color: #707070;
  }

  .goddess-rec .tt {
    text-align: center;
    padding: .5rem 0 .2rem;
  }

  .goddess-rec .tt span {
    display: inline-block;
    background: #ff7b80;
    color: #fff;
    padding: .1rem .3rem;
  }

  .goddess-rec .rec-li {
    float: left;
    width: 7rem;
    margin-left: .5rem;
    margin-top: .5rem;

  }
  .goddess-rec .rec-li .img {
    width:100%;
    height:8.6rem;
    overflow: hidden;
    position: relative;
  }

  .goddess-rec .rec-li .img img {
    width: 100%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }

  .goddess-rec a {
    color: #707070;
  }

  .goddess-rec .rec-t {
    padding-top: .2rem;
    padding-left: .2rem;
    width: 6.6rem;
    height: 1.8rem;
    line-height: .9rem;
    overflow: hidden;
    font-size: .6rem;

  }

  .goddess-rec .rec-li .price-b {
    margin-top: .3rem;
    padding-left: .2rem;

  }

  .goddess-rec .guanzhu {

  }

  .goddess-rec .shoucang img {
    width: .7rem;
  }

  .goddess-rec .fr {
    padding-right: .2rem;
  }

  .buy {
    position: fixed;
    width: 1.8rem;
    height: 1.8rem;
    background: url("../../assets/shop/buy.png");
    background-size: 100% 100%;
    bottom: 1rem;
    right: 1rem;
  }

  .brand-box {
    font-size: .6rem;
  }

  .brand-box .brand-tap {
    position: fixed;
    right: 0.15rem;
    top: 2rem;

  }
	.brand-box .brand-tap .tap li a{
		color: #707070;
	}
  .brand-box .brand-list {
    padding-right: 0.8rem;
  }

  .brand-box .sub-tt {
    background: #f3f3f3;
    color: #333333;
    font-weight: bold;
    padding-left: 0.8rem;
  }

  .brand-box .list {

    padding: .6rem 0.8rem;
    color: #707070;
    border-bottom: 1px solid #e6e6e6;
  }

  .brand-box .list .fl {
    width: 2.5rem;
    margin-right: 0.5rem;

  }

  .brand-box .list .fc {
    width: 10.5rem;
  }

  .brand-box .list .fl img {
    width: 2rem;
    height: 1rem;
    border: 1px solid rgba(7,17,27,0.1);
  }

  .type-box span.font {
    width: 60%;
    overflow: hidden;
  }

  .item-absolute {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 30;

  }

  .rec-no-product {
    padding-top: 5rem;
    text-align: center;
  }

  .shoucang {
    width: .7rem;
    height: .7rem;
    display: inline-block;
    background: url("../../assets/content/icoa3.png");
    background-size: 100% 100%;
  }

  .shoucang.active {
    width: .7rem;
    height: .7rem;
    display: inline-block;
    background: url("../../assets/content/icoa3-ac.png");
    background-size: 100% 100%;
  }

  .buy i {
    position: absolute;
    right: -5px;
    top: -5px;
  }
  .mint-cell {
    background-color: #fff;
    box-sizing: border-box;
    color: inherit;
    min-height: 60px;
    display: block;
    overflow: hidden;
    position: relative;
    text-decoration: none;
    border-bottom: 1px solid #e6e6e6;
  }
  .mint-cell:last-child{
  	border: 0;
  }
  .mint-cell img{
  	width: 1rem;
  	height: 1rem;
  }
  .color-red{
  	color:#ff7b80;
  }
  .background-red{
  	background:#ff7b80;
  }
</style>
